
local Config = require("Config")
local CopyConfig = require("excel.Map").copy
local CopyDefine = require("copy.Define")
local MiddleOpenDB = require("middle.MiddleOpenDB")
local ServerCommon = require("serverCommon.ServerCommonFW")
local MiddleLogic = require("middle.MiddleLogic")
local TeamLogic = require("team.TeamLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local CopyCommon = require("copy.CopyCommon")
local Human = require("core.Human")
local MPacketDefine = require("middle.MPacketDefine")
local Msg = require("core.Msg")
local DailyActFW = require("activity.DailyActFW")
local ActDefine = require("activity.Define")
local Timer = require("core.Timer")
local Copy = require("copy.CopyW")
local HtmlUtil = require("common.HtmlUtil")
local ChatHandlerW = require("chat.HandlerW")


 signHuman2CopyIDM = signHuman2CopyIDM or {}     -- 报名uuid->copyID
 
 --只存在跨服上
 signTeamDataM = signTeamDataM or {}          -- 跨服上的报名数据
 human2SignCopy = human2SignCopy or {}  -- {配置成功我副本和房间} uuid->{copyID, roomID}
 
SIGN_STATUS_MATCH     = 0
SIGN_STATUS_READY     = 1
SIGN_TEAM_COUNT_MAX = 3
NOT_READY_KICK_TIME = 10000         -- 10秒不准备自动踢出匹配队列

EXIT_SIGN_TYPE_NORMAL = 0  --主动退出
EXIT_SIGN_TYPE_CONDITON = 1 --条件不足退出
EXIT_SIGN_TYPE_TEAM    = 2  --被队长带退出
EXIT_SIGN_TYPE_NOREADY = 3  --没有准备被删出
EXIT_SIGN_TYPE_FINISH = 4 --匹配进副本成功后关掉界面
EXIT_SIGN_TYPE_TEAM_EXIT = 5 --队员退出队伍
EXIT_SIGN_TYPE_COPY_OTHER = 6



--检查是否跨服匹配
function checkCanSignMiddle(copyID) 
    if Config.IS_MIDDLE then
        return true
    end
    local config = CopyConfig[copyID]
    if not config then
        return
    end
    if config.type ~= CopyDefine.COPY_TYPE_TEAM then
        return
    end
    if config.middle ~= 1 then
        return
    end
    if not MiddleLogic.ENABLE_MIDDLE then
        return
    end
    if not MiddleOpenDB.isMiddleOpen() then
        return
    end
    local openDay = ServerCommon.getHadOpenDay()
    if config.middleDay + 1 > openDay then
        return
    end
    if _G.msg_middle_parse.check_connect() ~= true then
        return
    end
    return true
end

function checkCanEnterMiddle(human, copyID)
    local err = CopyCommon.checkEnterCondition(human, copyID)
    if err then
        return err
    end
    if not human2SignCopy[human._id] or human2SignCopy[human._id].copyID ~= copyID then
        return "error1"
    end
    if copyID == CopyDefine.COPY_GMTX_COPY_ID then
        if not DailyActFW.onCheckActIsRunning(ActDefine.ACT_TYPE_GMTX_ACT) then
            human2SignCopy[human._id] = nil           
            return "error2"
        end
    end
end

-- 离线处理
function onUserLogout(human)
    if not Config.IS_MIDDLE then
        if signHuman2CopyIDM[human._id] then
            signExit(human, signHuman2CopyIDM[human._id])
        end
    end
end

---- 游戏服逻辑 begin ----------------------------
local cache_list = {}
function sendSignMiddle(uuids, copyID, teamID)
    for k in pairs(cache_list) do
        cache_list[k] = nil
    end
    for i = 1, #uuids do
        local h = Human.onlineUuid[uuids[i]]
        cache_list[i] = {}
        cache_list[i].uuid = uuids[i]
        cache_list[i].svrIndex = Config.SVR_INDEX
        cache_list[i].name = "["..h.db.svrIndex%100000 .."]"..h.name
        cache_list[i].lv = h.db.lv
        cache_list[i].sex = h.db.sex
        cache_list[i].viewInfo = {}
        Human.makeViewInfo(cache_list[i].viewInfo, h.db.sex, Human.getRealBodyInfo(h.db))
        cache_list[i].teamID = teamID
        if teamID and i == 1 then
            cache_list[i].teamLeader = 1
        end        
    end
    
    _G.msg_middle_parse.writebegin(0)
    _G.msg_middle_parse.writeint(MPacketDefine.G2M_COPY_SIGN)
    _G.msg_middle_parse.writeint(copyID)
    _G.msg_middle_parse.writetable(cache_list)
    _G.msg_middle_parse.writeend()
end



-- 单人报名
local function signIn(human, copyID)  
    local err = CopyCommon.checkEnterCondition(human, copyID) 
    if err then
        Broadcast.sendBroadcast(human, Lang.MOUSE, err)
        return
    end    
    if copyID == CopyDefine.COPY_GMTX_COPY_ID then
        if not DailyActFW.onCheckActIsRunning(ActDefine.ACT_TYPE_GMTX_ACT) then
            Broadcast.sendBroadcast(human, Lang.DOWN, Lang.GMTX_NOT_START)  --活动暂未开启
            return
        end
    end
    sendSignMiddle({human._id}, copyID)
end


--组队报名
local function signTeam(human, copyID, team)
    local leaderUuid = TeamLogic.getLeaderUuid(team)
    if leaderUuid ~= human._id then -- 只有队长才能匹配       
        Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.COPY_TEAM_INVITE_CANNOT_MATCH_NOTLEADER)          
        return
    end    
    if copyID == CopyDefine.COPY_GMTX_COPY_ID then
        if not DailyActFW.onCheckActIsRunning(ActDefine.ACT_TYPE_GMTX_ACT) then
            Broadcast.sendBroadcast(human, Lang.DOWN, Lang.GMTX_NOT_START)  --活动暂未开启
            return
        end
    end
    local uuids = {}
    for i = 1, TeamLogic.TEAM_MAX_MEMBER_COUNT do
        if team[i] ~= nil and Human.onlineUuid[team[i].uuid] ~= nil  then
            if Human.onlineUuid[team[i].uuid].fd then
                local err = CopyCommon.checkEnterCondition(Human.onlineUuid[team[i].uuid], copyID) 
                if err then
                    if i > 1 then
                        err = "您的队友"..err
                    end
                    Broadcast.sendBroadcast(human, Lang.MOUSE, err)  
                    return
                end
                uuids[#uuids + 1] = team[i].uuid               
            end
        end
    end
    if #uuids  == 1 then --只有一个人的队伍
        TeamLogic.exit(human._id)
        signIn(human, copyID)
        return
    end    
    if #uuids == SIGN_TEAM_COUNT_MAX then --已经有3个人的。
        -- todo 优化
    end      
    sendSignMiddle(uuids, copyID, team.id)
end

--跨服组队副本报名
function sign(human, copyID)  
    local copyConfig = CopyConfig[copyID]    
    local team = TeamLogic.getTeamByUuid(human._id)  
    if team then
        signTeam(human, copyID, team)      
    else
        signIn(human, copyID)
    end  
end

function signExit(human, copyID)
    local copyConfig = CopyConfig[copyID]
    if not copyConfig or copyConfig.type ~= CopyDefine.COPY_TYPE_TEAM then
        return
    end
    _G.msg_middle_parse.writebegin(0)
    _G.msg_middle_parse.writeint(MPacketDefine.G2M_COPY_SIGN_EXIT)
    _G.msg_middle_parse.writeint(copyID)
    _G.msg_middle_parse.writestring(human._id)
    _G.msg_middle_parse.writeend()
end

function signReady(human, copyID)
    local copyConfig = CopyConfig[copyID]
    if not copyConfig or copyConfig.type ~= CopyDefine.COPY_TYPE_TEAM then
        return
    end
    local err = CopyCommon.checkEnterCondition(human, copyID) 
    if err then
        Broadcast.sendBroadcast(human, Lang.MOUSE, err)
        signExit(human, copyID)
        return
    end  
    _G.msg_middle_parse.writebegin(0)
    _G.msg_middle_parse.writeint(MPacketDefine.G2M_COPY_SIGN_READY)
    _G.msg_middle_parse.writeint(copyID)
    _G.msg_middle_parse.writestring(human._id)
    _G.msg_middle_parse.writeend()
    
    print("signReady:",copyID, human._id)
end

--招募
function ad(human, copyID)
    local copyConfig = CopyConfig[copyID]
    if not copyConfig or copyConfig.type ~= CopyDefine.COPY_TYPE_TEAM then
        return
    end
    if signHuman2CopyIDM[human._id] == nil then
        return
    end
    local name = copyConfig.name
    local diff = CopyCommon.getCopyDifficult(copyConfig.difficult)
    if diff then
        name = name.."-"..diff.."难度"
    end
    
    local content1 = string.format(Lang.COPY_TEAM_INVITE_AD, HtmlUtil.fontName(human.name, human._id), name, human._id, copyID, 0)
    Broadcast.sendBroadcast2World(Lang.WORLD, content1)
    
    local content2 = string.format(Lang.COPY_TEAM_INVITE_AD, "[" .. human.db.svrIndex%100000 .. "]" .. human.name, name, human._id, copyID, 0)
    local msgTable = {}
    msgTable.msg_type = 1
    msgTable.role_name = ""
    msgTable.msg = content2
    
    ChatHandlerW.LW_MIDDLE_CHAT(human, msgTable)
end


function M2G_COPY_SIGN_EXIT_RET(fd, msg)
   local human = Human.onlineUuid[msg.uuid]
   if human and human.fd then
      local mm = Msg.gc.GC_COPY_TEAM_SIGN_EXIT
      mm.copyID = msg.copyID
      mm.exitType = msg.exitType
      Msg.send(mm, human.fd)
   end
   
   print("M2G_COPY_SIGN_EXIT_RET:",msg.uuid)
   signHuman2CopyIDM[msg.uuid] = nil
end

function M2G_COPY_SIGN_LIST(fd, mm)
    local msg = Msg.gc.GC_COPY_TEAM_SIGN_LIST
    local copyConfig = CopyConfig[mm.copyID]
    msg.copyID = mm.copyID
    msg.difficult = copyConfig.difficult
    msg.name = copyConfig.name
    local ids = {}
    local match = mm.list
    local len = 0
    for i = 1, #match do
        if match[i].svrIndex == Config.SVR_INDEX then
            local human = Human.onlineUuid[match[i].uuid]
            if human and human.fd then
                len = len + 1
                msg.members[len].uuid = match[i].uuid
                msg.members[len].name = match[i].name
                msg.members[len].sex = human.db.sex
                Human.makeViewInfo(msg.members[len].viewInfo, human.db.sex, Human.getRealBodyInfo(human.db))
                msg.members[len].status = match[i].status
                msg.members[len].lv = match[i].lv
                ids[#ids + 1] = human.fd                            
            end
            signHuman2CopyIDM[match[i].uuid] = msg.copyID   
         else
            len = len + 1
            msg.members[len].uuid = match[i].uuid
            msg.members[len].name = match[i].name
            msg.members[len].sex  = match[i].sex
            msg.members[len].status = match[i].status
            msg.members[len].lv = match[i].lv
            for k,v in pairs(match[i].viewInfo) do
                msg.members[len].viewInfo[k] = v
            end
         end
    end
    msg.members[0] = len
    ids[0] = #ids
    if ids[0] > 0 then
      Msg.sendMulti(msg, ids)
    end
end

function M2G_COPY_SIGN_READY(fd, msg)
    local human =  Human.onlineUuid[msg.uuid]
    if human and human.fd then
        local mm = Msg.gc.GC_COPY_TEAM_LEADER_READY
        mm.copyID = msg.copyID
        mm.second = NOT_READY_KICK_TIME/1000
        mm.leaderUuid = msg.leaderUuid
        Msg.send(mm, human.fd)
    end
end

function M2G_COPY_SIGN_ERR(fd, msg)
    local human = Human.onlineUuid[msg.uuid]
    if human and human.fd then
        Broadcast.sendBroadcast(human, msg.type, msg.err)
    end
end

function M2G_COPY_SIGN_ROOM_OK(fd, msg)
    local human = Human.onlineUuid[msg.uuid]
    if human and human.fd then
        local err = CopyCommon.checkEnterCondition(human, msg.copyID) 
        if err then
            Broadcast.sendBroadcast(human, Lang.MOUSE, err)
            return
        end  
        if not MiddleLogic.enter(human, "", msg.copyID) then
            print("M2G_COPY_SIGN_ROOM_OK:", msg.copyID, msg.uuid)
        end
    end
end
---- 游戏服逻辑 end -------------------------------------------------

---- 跨服中逻辑start -----------------------------------------------
--
--
local function findSignDataM(uuid, copyID)
    signTeamDataM[copyID] = signTeamDataM[copyID] or {}
    local signData = signTeamDataM[copyID]
    for i = 1, #signData do
        for j = 1, #signData[i] do
            if signData[i][j].uuid == uuid then
                return signData[i], i
            end
        end
    end  
end 

local function changeStatusM(match, status)
    for i = 1, #match do
        match[i].status = status
    end
end

local function sendMiddleBroadcast(fd, uuid, type, err)
    _G.msg_middle_parse.writebegin(fd)
    _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_ERR)
    _G.msg_middle_parse.writestring(uuid)
    _G.msg_middle_parse.writeint(type)
    _G.msg_middle_parse.writestring(err)
    _G.msg_middle_parse.writeend() 
end

local function checkSourceSrvMiddle()

end
local sourceSvrIndex = {}
function sendSignListM(copyID, match)
    for k in pairs(sourceSvrIndex) do
        sourceSvrIndex[k] = nil
    end
    local len = 0
    for i = 1, #match do
        sourceSvrIndex[match[i].svrIndex] = 1
    end
    
    for k,_ in pairs(sourceSvrIndex) do
        local fd = MiddleLogic.getFDBySvrIndex(k)
        if fd then
          _G.msg_middle_parse.writebegin(fd)
          _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_LIST)
          _G.msg_middle_parse.writeint(copyID)
          _G.msg_middle_parse.writetable(match)
          _G.msg_middle_parse.writeend()
        end       
    end
end


function G2M_COPY_SIGN(fd, msg)
    if not Config.IS_MIDDLE then return end    
    for i = 1, #msg.list do --删掉已有匹配
        if signHuman2CopyIDM[msg.list[i].uuid] then
            exitM(msg.list[i].uuid, signHuman2CopyIDM[msg.list[i].uuid], EXIT_SIGN_TYPE_TEAM)
        end   
    end
    for i = 1, #msg.list do     
        signHuman2CopyIDM[msg.list[i].uuid] = msg.copyID
    end    
    signTeamDataM[msg.copyID] = signTeamDataM[msg.copyID] or {}
    local data = signTeamDataM[msg.copyID]
    local match    
    if #msg.list == 1 then --单人匹配
        local avg = 10000
        local lv = msg.list[1].lv
        for i = 1, #data do  --先找只差一个人的
            if SIGN_TEAM_COUNT_MAX - #data[i] == 1 then
                local sum = lv
                for j = 1, #data[i] do
                    sum = data[i][j].lv + sum
                end
                local avgVal = math.abs(sum/SIGN_TEAM_COUNT_MAX - lv)
                if avgVal < avg then
                    match = data[i]
                    avg = avgVal
                end
            end
        end
        if match then
            match[#match+1] = msg.list[1]
            msg.list[1].status = SIGN_STATUS_MATCH
            sendSignListM(msg.copyID, match)
            return
        end
        for i = 1, #data do  --匹配其它
            match = data[i]
            if #match < SIGN_TEAM_COUNT_MAX then
                match[#match+1] = msg.list[1]
                msg.list[1].status = SIGN_STATUS_MATCH
                sendSignListM(msg.copyID, match)
                return
            end
        end
        data[#data + 1] = {}  --都满了，新建一个
        data[#data][1] = msg.list[1]
        msg.list[1].status = SIGN_STATUS_MATCH
        match = data[#data]
        sendSignListM(msg.copyID, match)
        return 
    end
    if #msg.list < SIGN_TEAM_COUNT_MAX then
        --匹配多人
        local sumLv = 0
        for i = 1, #msg.list do
            sumLv = sumLv + msg.list[i].lv
        end    
        sumLv = sumLv /2
        local diffLv = 10000
        for i = 1, #data do  -- 2找1
            if #data[i] == 1 then
                if math.abs(sumLv - data[i][1].lv) < diffLv then
                    match = data[i]
                    diffLv = math.abs(sumLv - data[i][1].lv)
                end
            end
        end
    end
    if not match then
        data[#data + 1] = {} 
        match = data[#data]
    end
    for i = 1, #msg.list do
            match[#match + 1] = msg.list[i]
            msg.list[i].status = SIGN_STATUS_MATCH
    end     
    sendSignListM(msg.copyID, match)        
end

function removeM(uuid, copyID, match, index)
    if signHuman2CopyIDM[uuid] ~= copyID then
        return
    end 
    local signData = signTeamDataM[copyID]
    if not match or not index then
        match, index = findSignDataM(uuid, copyID)
    end   
    if not match then
        signHuman2CopyIDM[uuid] = nil
        return
    end
    local my
    for i = #match, 1, -1 do
        if match[i].uuid == uuid then
              my = match[i]
              break
        end
    end
    local removeUuids = {}
    if my.teamLeader and my.teamID then --队长退出匹配，队员也要退出
        for i = #match, 1, -1 do
            if my.teamID == match[i].teamID then
                removeUuids[#removeUuids + 1] = {uuid = match[i].uuid, sourceSvrIndex = match[i].svrIndex}
                signHuman2CopyIDM[match[i].uuid] = nil
                match[i] =match[#match]
                match[#match] = nil
            end
        end
    else -- 删除个人
        for i = #match, 1, -1 do  
            if match[i].uuid == uuid then
                removeUuids[1] = {uuid = match[i].uuid, sourceSvrIndex = match[i].svrIndex}
                match[i] = match[#match]
                match[#match] = nil                
                signHuman2CopyIDM[uuid] = nil
                break
            end
        end
    end
    if #removeUuids > 0 then
        if #match > 0 then
            match[1].startTime = nil
            match[1].applyRoom = nil
            changeStatusM(match, SIGN_STATUS_MATCH)
            sendSignListM(copyID, match)
        else
            signData[index] = signData[#signData]
            signData[#signData] = nil
        end
        return removeUuids
    end
end

--玩家从匹配中删除，并通知到玩家
function exitM(uuid, copyID, type, match, index)
    local removeUuid = removeM(uuid, copyID, match, index)    
    if removeUuid and #removeUuid > 0 then
        local fd
        local retType
        for i = 1, #removeUuid do
            fd = MiddleLogic.getFDBySvrIndex(removeUuid[i].sourceSvrIndex)
            if fd then
                 _G.msg_middle_parse.writebegin(fd)
                 _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_EXIT_RET)
                 _G.msg_middle_parse.writeint(copyID)
                 _G.msg_middle_parse.writestring(removeUuid[i].uuid)    
                 if type == EXIT_SIGN_TYPE_NORMAL then
                    retType = uuid == removeUuid[i].uuid and EXIT_SIGN_TYPE_NORMAL or EXIT_SIGN_TYPE_TEAM
                 else
                    retType = type
                 end        
                 _G.msg_middle_parse.writeint(retType)
                 _G.msg_middle_parse.writeend()
            end
        end
        return true       
    end
end

function removeAllM(copyID, match, index)
    local msg = Msg.gc.GC_COPY_TEAM_SIGN_EXIT
    msg.copyID = copyID
    msg.exitType = EXIT_SIGN_TYPE_TEAM_EXIT
    local fd
    for i = 1, #match do
         fd = MiddleLogic.getFDBySvrIndex(match[i].svrIndex)
         if fd then
            _G.msg_middle_parse.writebegin(fd)
            _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_EXIT_RET)
            _G.msg_middle_parse.writeint(copyID)
            _G.msg_middle_parse.writestring(match[i].uuid)           
            _G.msg_middle_parse.writeint(EXIT_SIGN_TYPE_TEAM_EXIT)
            _G.msg_middle_parse.writeend()
         end
    end
    local signData = signTeamDataM[copyID]
    if signData then
      signData[index] = signData[#signData]
      signData[#signData] = nil
    end
end

function startCopyM(uuid, copyID, match, index)
    if match[1].uuid ~= uuid then --非队长，不能开启
        return
    end
    match[1].status = SIGN_STATUS_READY
    local len = 0
    for i = 1, #match do
        local fd = MiddleLogic.getFDBySvrIndex(match[i].svrIndex)
        if not fd then
            exitM(match[i], copyID, EXIT_SIGN_TYPE_NORMAL, match, index) 
            return
        end
    end
    for i = 1, #match do
        local fd = MiddleLogic.getFDBySvrIndex(match[i].svrIndex)
        _G.msg_middle_parse.writebegin(fd)
        _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_READY)
        _G.msg_middle_parse.writeint(copyID)
        _G.msg_middle_parse.writestring(match[i].uuid)        
        _G.msg_middle_parse.writestring(uuid)
        _G.msg_middle_parse.writeend()        
    end
    match[1].startTime = Timer.now + NOT_READY_KICK_TIME
    match[1].status =  SIGN_STATUS_READY
    match[1].applyRoom = nil
end

--正式开始申请副本
function realStartCopyM(copyID, match, index)
    local ids = {}
    local len = 0
    for i = 1, #match do
        len = len + 1
        ids[len] = match[i].uuid
    end
    len = 0
    for i = 1, #match do
        if match[i].status ~= SIGN_STATUS_READY then
            len = len + 1
            ids[len] = match[i].uuid
        end
    end
    for i = 1, len do
        exitM(ids[i], copyID, EXIT_SIGN_TYPE_NOREADY, match, index) 
    end
    if len > 0 then
        if #match > 0 then
            sendSignListM(copyID, match)
        end
        return
    end
    match[1].applyRoom = copyID
    Copy.applyCopyRoomM(match[1].uuid, copyID, os.time())
    
     print("realStartCopy:",copyID, match[1].uuid)
end


function finishApplyCopyRoomM(uuid, realCopyID, roomID)
    if roomID == 0 then
        return
    end
    local copyID = signHuman2CopyIDM[uuid]
    if copyID == nil then
        return
    end
    local match, index = findSignDataM(uuid, copyID)
    if not match then
        return
    end
    if match[1].uuid ~= uuid or match[1].applyRoom ~= realCopyID then
        return 1 --已经变了，去掉
    end
    if roomID == 0 then          
        local fd = MiddleLogic.getFDBySvrIndex(match[1].svrIndex)
        if fd then
            sendMiddleBroadcast(fd, uuid,Lang.TEAM+Lang.DOWN, Lang.COPY_ENTER_ERR_COPY_FULL)
        end
        match[1].startTime = nil
        match[1].applyRoom = nil
        changeStatusM(match, SIGN_STATUS_MATCH)
        sendSignListM(copyID, match)
        return 1
    end
    local ids = {}
    for i = 1, #match do
        ids[#ids + 1] = match[i].uuid
    end
    for i = 1, #match do
        human2SignCopy[match[i].uuid] = {copyID = realCopyID, roomID = roomID, time = Timer.now, members = ids}
        signHuman2CopyIDM[match[i].uuid] = nil
    end
    signTeamDataM[copyID][index] = signTeamDataM[copyID][#signTeamDataM[copyID]]
    signTeamDataM[copyID][#signTeamDataM[copyID]] = nil
    for i = 1, #match do
        local fd = MiddleLogic.getFDBySvrIndex(match[i].svrIndex)
        if fd then
            _G.msg_middle_parse.writebegin(fd)
            _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_ROOM_OK)
            _G.msg_middle_parse.writestring(match[i].uuid) 
            _G.msg_middle_parse.writeint(realCopyID)
            _G.msg_middle_parse.writeint(roomID)              
            _G.msg_middle_parse.writeend()   
            _G.msg_middle_parse.writebegin(fd)
            _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_EXIT_RET)
            _G.msg_middle_parse.writeint(copyID)
            _G.msg_middle_parse.writestring(match[i].uuid)    
            _G.msg_middle_parse.writeint(EXIT_SIGN_TYPE_FINISH)
            _G.msg_middle_parse.writeend()   
            print("ok:", match[i].svrIndex, copyID, match[i].uuid)   
        end       
    end
    return 2
end

function middleTeamCopyRoom(human, copyID)
    local info = human2SignCopy[human._id] 
    if info and info.copyID == copyID and Copy.roomDatas[copyID] then
         human2SignCopy[human._id] = nil
         local data = Copy.roomDatas[copyID][info.roomID] 
         if data and data.finishCode == nil then
             local msg = Msg.wl.WL_CROSS_ROOM_APPLY_RESULT
             msg.copyid = copyID
             msg.roomid = info.roomID
             Msg.send2logic(msg, human._id)  
             local team = TeamLogic.getTeamByUuid(human._id)
             if team then
                TeamLogic.exit(human._id)
                team = nil
             end
             for i = 1, #info.members do
                team = TeamLogic.getTeamByUuid(info.members[i])
                if team then
                    break
                end
             end
             if team then
                TeamLogic.addMember(team, human)
             else
                TeamLogic.create(human)  
                team = TeamLogic.getTeamByUuid(human._id)
                info = {}
                info.copyID = copyID
                info.roomID = info.roomID
                info.startTime = os.time()
                data.teamID = team.id
                Copy.copyTeam2Copy[team.id] = info
             end
             return
         end
    end
    --没有，直接退回本服
    MiddleLogic.leave(human)
end

function G2M_COPY_SIGN_EXIT(fd, msg)
    if signHuman2CopyIDM[msg.uuid] ~= msg.copyID then
       return       
    end
    if exitM(msg.uuid, msg.copyID, EXIT_SIGN_TYPE_NORMAL) then
       return
    end
    _G.msg_middle_parse.writebegin(fd)
    _G.msg_middle_parse.writeint(MPacketDefine.M2G_COPY_SIGN_EXIT_RET)
    _G.msg_middle_parse.writeint(msg.copyID)
    _G.msg_middle_parse.writestring(msg.uuid)
    _G.msg_middle_parse.writeint(EXIT_SIGN_TYPE_NORMAL)
    _G.msg_middle_parse.writeend()    
end



function G2M_COPY_SIGN_READY(fd, msg)
    if signHuman2CopyIDM[msg.uuid] ~= msg.copyID then
        return
    end
    local match, index = findSignDataM(msg.uuid, msg.copyID)
    if not match then
        return --处理
    end
    if msg.copyID == CopyDefine.COPY_GMTX_COPY_ID then
        if not DailyActFW.onCheckActIsRunning(ActDefine.ACT_TYPE_GMTX_ACT) then
            removeAllM(msg.copyID, match, index)
            return
        end
    end
    
    if match[1].uuid == msg.uuid then --队长。
        return startCopyM(msg.uuid, msg.copyID,match, index)
    end
    local pos 
    for i = 1, #match do
        if match[i].uuid == msg.uuid and match[i].status == SIGN_STATUS_MATCH then                  
            match[i].status = SIGN_STATUS_READY         
            pos = i    
            break
        end
    end
    sendSignListM(msg.copyID, match)
end

-- 1s定时器
timer_cnt = timer_cnt or 0
function onTimer1Second()
    local cnt = 0
    timer_cnt = timer_cnt + 1
    for copyID, signData in pairs(signTeamDataM) do
        for i = #signData, 1, -1 do
            local members = signData[i]
            if members[1].startTime and Timer.now >= members[1].startTime and members[1].applyRoom == nil then
                realStartCopyM(copyID, members, i)
                cnt = cnt + 1
            end
        end
    end
    
    if timer_cnt > 5 then 
        timer_cnt = 0     
        for uuid, data in pairs(human2SignCopy) do
            if data.time + 120000 < Timer.now then
                human2SignCopy[uuid] = nil
            end
        end
    end
end
---- 跨服中逻辑end ----
